// 函数组件
import React, { useState, useEffect, useContext,useLayoutEffect } from 'react';
import { ExclamationCircleFilled } from '@ant-design/icons';
import { ConfigProvider, Form, Input, Button, Table, Switch, Select, DatePicker, Space, Modal } from 'antd';
import { useNavigate } from 'react-router-dom';
import DiscountAlter from './child/DiscountAlter'
import zh_CN from 'antd/es/locale/zh_CN';
import type { ColumnsType } from 'antd/es/table';
import type { DatePickerProps } from 'antd';
import './Css/Promontion.less'
import '../../css/public.less'
import type { PaginationProps,Pagination } from 'antd';
//添加抵扣管理弹框
import AddBoxAlter from './child/AddBoxAlter';
// 获取当前页面的总数居
import { deductionApi,deductionSearchApi,deTypeApi,DelDeductionApi,changeDeductionStateApi } from '../../../api/wj'
import { number } from 'echarts';


function Deduction() {
    //表格数据类型
    interface DataType {
        key: React.Key; //序号
        deId:number;//后端ID号
        deTitle: string; //标题 name
        deStandard: string;//折扣标准 discount
        deType: number; //实用行程ID route 
        deState: number //以未上架判断 state
        deCreate: string; //添加时间 AddTime
        sportName?:string //适用行程名
    }
    const { confirm } = Modal;
    //查看弹框显示布尔值
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isModalOpen1, setIsModalOpen1] = useState(false);
    // //路由跳转
    // const navigate = useNavigate()
    //input 值
    const [title, setTitle] = useState<string | null>('')
    // 日期 值
    const [date, setDate] = useState<string | null>('')
    //select 值
    const [state, setState] = useState<number>()
    //当前页码
    const [nowPage, setNowPage] = useState<number | undefined | null>(1)
    //总条数
    const [totalPage,setTotalPage] = useState<number | undefined | null>(5)
    const columns: ColumnsType<DataType> = [
        {
            title: '序号',
            dataIndex: 'deId',
            width: 90,
            align: 'center'
        },
        {
            title: '标题',
            dataIndex: 'deTitle',
            align: 'center'
        },
        {
            title: '折扣标准',
            dataIndex: 'deStandard',
            align: 'center'
        },
        {
            title: '实用行程',
            dataIndex: 'sportName',
            align: 'center'
        },
        {
            title: '是否上架',
            dataIndex: 'deState',
            align: 'center',
            render: (_, v) =>
            (
                <Switch
                    // 对上下架进行判断
                    defaultChecked={v.deState===1?true:false}
                    onChange={onChange}
                    onClick={() => { switchClick(v) }} />
            )
        },
        {
            title: '添加时间',
            dataIndex: 'deCreate',
            align: 'center'
        },
        {
            title: '操作',
            dataIndex: 'address',
            width: 200,
            align: 'center',
            render: (_, v) => (
                <div className='operationList'>
                    {/* <button className='man' onClick={() => { commodityBtn(v) }}>商品管理</button> */}
                    <button className='edit' onClick={() => { redactBtn(v) }}>编辑</button>
                    <button className='del' onClick={() => { showPromiseConfirm(v.deId) }}>删除</button>
                </div>
            )
        },
    ];
    //用户数据
    const [data,setData] = useState<DataType[]>()
    //用户数据
    const [newdata,setNewData] = useState<DataType[]>()
    //排序的方式名
    const [sortName, setSortName] = useState<{ value: string, label: string }[]>([{ value: '升序', label: '升序' }, { value: '降序', label: '降序' }])
    //编辑详情存储
    const [edit3, setEdit3] = useState<DataType>()

    interface SelectType{
        state:number, 
        name:string
    }
    //select下拉选项框里的具体选项
    const [switchList, setSwitchList] = useState<SelectType[]>([{state:1,name:'上架'},{state:0,name:'下架'}])

    //实用行程总数据
    const [types,setTypes] = useState<{sportId:number,sportName:string}[]>()
    interface searchProps {
        title: string | null, 
        state: number | null | undefined, 
        date: string |null,
        num:number| null | undefined,
        size:number| null | undefined
    }
    //总筛选需要的内容
    const [searchList, setSearchList] = useState<searchProps>({
        title: null,
        state: null,
        date: null,
        num: null,
        size: null
    })
    const [count,setCount] = useState<number>()
    //添加抵扣管理
    const addBox =()=>{
        //让弹框显示
        setIsModalOpen1(true)
    }
    //关闭抵扣管理
    const delBox = ()=>{
        setIsModalOpen1(false)
    }
    //父组件获取子组件传过来的值
    const getChild=()=>{
    }
    //表格方法
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    //switch 的布尔值判断
    const [switch1, setSwitch1] = useState<boolean[]>([])

    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        //switch勾选的内容
        console.log('selectedRowKeys changed switch勾选的内容: ', newSelectedRowKeys);
        console.log('React', data);
        setSelectedRowKeys(newSelectedRowKeys);
    };
    // const hasSelected = selectedRowKeys.length > 0;
    //选项框的值
    const { Option } = Select;


//onGenderChang选项框事件
const onGenderChange = (value: string | number) => {
    console.log('onGenderChange===>',value);
    let newList = switchList.filter(item => item.name == value )
    // 筛选出来的对象
    console.log(newList[0]);
    let obj = newList[0]
    setState(obj.state)
    console.log('state', state);
    

    };
    //input 输入框的值
    const onInputChange = (e: any) => {
        // console.log('input的值',e.target.value);
        let name = e.target.value
        setTitle(name)
        console.log('name', name);
    }
    //页页码发生改变
    const changePage = (page: number, pageSize: number): void => {
        console.log('页码变了了', page, pageSize);
        setNowPage(page),
        setTotalPage(pageSize)
    }
    //调用获取参数
    useEffect(() => {
        value()
    }, [nowPage,totalPage])
    //获取当页总数据
    const value = async () => {
        try {
            let data:any = { num: nowPage, size: totalPage }
            // num第几页 size 一页好多条
            let res = await deductionApi(data)
            // console.log('页码数据成功的函数', res);
            if(res.code == '200'){
                // console.log('200后的数据',res.data.data);
                setData(res.data.data);
                setCount(res.data.total);
                let res2 = await deTypeApi()
                console.log('第二次请求的结果',res2.data);
                if(res2.code=='200'){
                    setTypes(res2.data)
                    // setSwitchList(res2.data)
                }
            }
        } catch (err) {
            console.log(err);
        }
    }
    //遍历的新数据
    useEffect(()=>{
        let newList = data?.map(item=>{
            types?.forEach(item2=>{
                if(item.deType == item2.sportId){
                    item.sportName = item2.sportName
                }
            })
            return item
        })
        // console.log("new",newList);
        setNewData(newList)
        // setData(newList)
    },[data,types])
    //获取
    const rowSelection = {
        // selectedRowKeys,
        onChange: onSelectChange,
    };


    //日期选择
    const onChangeDate = (date: any,timeString: string) => {
        // console.log(dateString);
        setDate(timeString)
        console.log('data,timeString', date,timeString);
    };
    //switch的change方法
    const onChange = (checked: boolean) => {
        // checked ? checked=true:checked=false
        console.log(`switch to ${checked} `);
    };
    //删除函数
    const showPromiseConfirm = (v:any) => {
        confirm({
            title: '确认删除此信息',
            icon: <ExclamationCircleFilled />,
            content: 'When clicked the OK button, this dialog will be closed after 1 second',
            onOk() {
                return new Promise((resolve, reject) => {
                    setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
                    console.log(v);
                    
                    DelDeductionApi({id:v}).then(res=>{
                        console.log('删除成功',res);
                        if(res.code=='200'){
                            //重新获取数据
                            value()
                        }
                    }).catch(err=>{
                        console.log('删除失败',err);
                        
                    })
                }).catch(() => console.log('Oops errors!'));
            },
            onCancel() {},
        });
    };
    //更改上架状态
    const switchClick = (v: any) => {
        console.log(`switchClick事件获取到的`, v.deId);
        let id = Number(v.deId)
        changeDeductionStateApi({id:id}).then(res=>{
            console.log('该状态成功',res);
            if(res.code=='200'){
                value()
            }
        }).catch(err=>{
            console.log('err该状态报错',err);
            
        })
    }
    //点击编辑
    const redactBtn = (v: DataType) => {
        console.log('点击编辑事件触发的', v)
        setEdit3(v)
        setIsModalOpen(true)
    }
    useEffect(() => {
        setSearchList({
            title:title,
            state: state,
            date: date,
            num:nowPage,
            size:totalPage
        })
    }, [title, state, date])
    const filtrateBtn = () => {
        setSearchList({
            title:title,
            state: state,
            date: date,
            num:nowPage,
            size:totalPage
        })
        //抵扣管理 模糊查询（暂时挑的数据库里面的数据查）
        deductionSearchApi(searchList).then((res)=>{
            // console.log('迷糊查询成功',res);
            if(res.code == '200'){
                console.log('迷糊查询成功的数据',res.data.data[0]);
                let data2 = newdata?.filter(item=>{
                    return item.deId == res.data.data[0].id
                })
                // console.log('晒出来的data2',data2);
                setNewData(data2)
                
            }
        })
        // console.log('搜索的内容', searchList);
    }
    //重置按钮
    const rest = () => {
        value()
    }
    //让位置弹框关闭
    const closeModal = () => {
        setIsModalOpen(false)
    }
    return (
        <div className='Promotionma'>
            {/* 头部 */}
            <div className='page-top'>
                <div className='page-title'>
                    <p>折扣管理</p>
                </div>
            </div>

            {/* 内容框 */}
            <div className='page-content'>
                {/* 查询部分 */}
                <div className='filtrate-search'>
                    <p className='title'>筛选查询</p>
                    <div className='inputBox'>
                        <div>
                            <p>关键词：</p>
                            <Input
                                placeholder="输入关键词"
                                onChange={onInputChange}
                            />
                        </div>
                        <div>
                            <p>状态：</p>
                            <Select
                                placeholder="请选择状态"
                                onChange={onGenderChange}
                                allowClear
                            >
                                {/* <Option value="male">male</Option>
                                <Option value="female">female</Option>
                                <Option value="other">other</Option> */}
                                {switchList.map(item => {
                                    return <Option key={item.state} value={item.name}>{item.name}</Option>
                                })}
                            </Select>
                        </div>
                        <div>
                            <p className='dataT'>添加时间：</p>
                            <DatePicker onChange={onChangeDate} renderExtraFooter={() => 'extra footer'} showTime />
                        </div>
                    </div>
                    <div className='buttonType'>
                        <button className='reset' onClick={rest}>重置</button>
                        <button className='filter' onClick={filtrateBtn}>筛选</button>
                    </div>
                </div>
                {/* 数据表格部分 */}
                <div className='data-list'>
                    <div className='headChoose'>
                        {/* 标题 */}
                        <p>数据列表</p>
                        <div>
                            {/* 排序方式 */}
                            <p style={{ marginRight: "10px" }}>排序方式:</p>
                            <Select
                                style={{ width: 120 }}
                                options={sortName}
                            />
                            {/* 批量操作 */}
                            <button className='delBtn' style={{ margin: "0 10px" }}>批量删除</button>
                            {/* 添加按钮 */}
                            <button className='add' onClick={addBox}>添加</button>
                        </div>
                    </div>
                    <div className='contentType'>
                        <div style={{ marginBottom: 16 }}>
                        </div>
                        <ConfigProvider locale={zh_CN}>
                            <Table
                                rowSelection={rowSelection}
                                columns={columns}
                                dataSource={newdata}
                                rowKey={item=>item.deId}
                                scroll={{ y: 444 }}
                                pagination={{
                                    position: ['bottomCenter'],
                                    defaultPageSize: 5,
                                    // current:1,
                                    // pageSize:5,
                                    total:count,
                                    pageSizeOptions: [3, 5, 10, 15],
                                    showQuickJumper: true,
                                    showSizeChanger: true,
                                    onChange: changePage
                                }} />
                            <DiscountAlter isModalOpen={isModalOpen} closeModal={closeModal} edit3={edit3} switchList={switchList} value={value}></DiscountAlter>
                            {/* 添加抵扣管理 */}
                            <AddBoxAlter isModalOpen1={isModalOpen1} delBox={delBox} getChild={getChild} value={value}></AddBoxAlter>
                        </ConfigProvider>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default Deduction
//抵扣管理页面